package edu.ucsd.ccdb.rightClickPopupUtil;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import edu.ucsd.irods.IRODSFileString;
import edu.ucsd.irods.IRODSOperation;

/*
 * Create new folder right click and hide/display the options
 */
public class CreateNewFolderListener implements ActionListener {

	private JFrame frame ; 
	private JTree tree;
	
	public CreateNewFolderListener ( JFrame frame, JTree tree) {
		this.frame = frame;
		this.tree = tree;

	}
	
	public void actionPerformed(ActionEvent e) {
		
		//validation check if the selected node is a file
		// change the option disabled if select a file

		String folderName = (String) JOptionPane.showInputDialog( frame,
												"Enter the folder name: ",
												"New Folder", JOptionPane.PLAIN_MESSAGE,
												null,null, "" );
		
		System.out.println ("User enter: " + folderName );
		
		
		TreePath selectedPath= tree.getSelectionPath() ;
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
			
		IRODSFileString file = (IRODSFileString) node.getUserObject();
		
		if ( !file.isDirectory() ) {
			System.out.println ("Create folder on file. Nothing done");
			return;
		}

		try{
			IRODSOperation.createDir( file.getAbsolutePath() , folderName);
			
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		//do animation
		IRODSFileString irodsFile = new IRODSFileString( file.getAbsolutePath() + "/" + folderName 
									, folderName, true);
		DefaultMutableTreeNode newTreeNode = new DefaultMutableTreeNode(irodsFile);
		
		// add to the tree
		DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
		model.insertNodeInto(newTreeNode, node, node.getChildCount() );
	}
}	